# -*- coding: UTF-8 -*-

import os
import requests
from requests_toolbelt import MultipartEncoder

import config
import pandas as pd
import json
import re

# 导入自定义包
import api
import config
import utils

# 导入格式规范包
import sys
from typing import List
if sys.version_info.minor >= 8:
    from typing import Literal
else:
    from typing_extensions import Literal

from pprint import pprint
   
def upload_file(file_name:str,file_path:str,folder_token:str):
    
    # 上传文件到Lark 共享空间
    client = api.Client(config.LARK_HOST)
    tenant_access_token = client.get_tenant_access_token(config.APP_ID,config.APP_SECRET)
   
    
    file_size = os.path.getsize(file_path)
    
    url = "https://open.larksuite.com/open-apis/drive/v1/files/upload_all"
    form = {'file_name': file_name,
            'parent_type': 'explorer',
            'parent_node': folder_token,
            'size': str(file_size),
            'file': (open(file_path, 'rb'))}  
    multi_form = MultipartEncoder(form)
    headers = {
        'Authorization': 'Bearer '+ tenant_access_token ,  ## 获取tenant_access_token, 需要替换为实际的token
    }
    headers['Content-Type'] = multi_form.content_type
    #print(headers)
    response = requests.request("POST", url, headers=headers, data=multi_form)
    return response.json()

def upload_coa(code:str,batch:str):
    # 赋值
    folder_token = config.folder_token[code[:2]]
    #folder_token = config.folder_token['COA'] #测试用
    file_name = f'BKD - {code} {batch} COA.pdf'
    file_path = os.path.join(config.COA_PATH,file_name)
    
    # 如果没有转换pdf，转换一下
    if not os.path.exists(file_path):
        docx_path = os.path.join(config.COA_PATH,f'BKD - {code} {batch} COA.docx')
        if os.path.exists(docx_path):
            file_path = utils.conver2pdf(docx_path)
        else:    
            print(f'{docx_path} not found')
    
    # 上传coa，
    # 如果成功，返回filetoken
    # 如果失败，返回错误码
    pprint({'filename':file_name,
            'file path':file_path,
            'folder token':folder_token})
    
    response = upload_file(file_name,file_path,folder_token)
    #print(type(response['code']))
    if response['code'] == 0:
        file_token = response['data']['file_token']
        return file_token
    else: return response['code']
    
def update_test_report_record(record_id,file_name,file_token):
    base = api.Base(config.LARK_HOST)
    access_token = base.get_tenant_access_token(config.APP_ID,config.APP_SECRET)
    payload = json.dumps({
        "fields": {
            "COA file": {
                "link": f'https://eog1g9c5x2d.jp.larksuite.com/file/{file_token}',
                "text": file_name
            }
        }
    })
    resp =base.update_record(access_token,
                       table_id=config.TEST_REPORT_TABLE_ID,
                       record_id=record_id,
                       payload=payload)
    return resp

# def update_test_report_record(record_id,file_name,file_token):
#     client = api.Client(config.LARK_HOST)
#     tenant_access_token = client.get_tenant_access_token(config.APP_ID,config.APP_SECRET)
    
#     url = f"{config.LARK_HOST}/open-apis/bitable/v1/apps/{config.APP_TOKEN}/tables/{config.TEST_REPORT_TABLE_ID}/records/{record_id}"
#     payload = json.dumps({
#         "fields": {
#             "COA file": {
#                 "link": f'https://eog1g9c5x2d.jp.larksuite.com/file/{file_token}',
#                 "text": file_name
#             }
#         }
#     })
#     headers = {
#     'Content-Type': 'application/json',
#     'Authorization': 'Bearer '+ tenant_access_token
#     }
#     response = requests.request("PUT", url, headers=headers, data=payload).json()
    
#     return response['code']
    
def upload_documents():
    pass
    
if __name__ == "__main__":
    code = 'RA0215'
    batch = 'RA22070803'
    record_id = 'reclSkkyR6'
    filename = 'test.pdf'
    filetoken = 'BFEobP4zIoXwcaxsv40jfekXp7d'
    m = update_test_report_record(record_id,filename,filetoken)
    print(m)
    
